package app.model


import scala.collection.immutable.HashMap
import im.mange.shoreditch.engine.services.Service
import im.mange.shoreditch.engine.systems.System
import im.mange.shoreditch.engine.{Json, HttpClient}

//TODO: is this used .. seems to have a strange name ..
case class raw(systems: Seq[System]) {
  private val supportedServiceTypes = List("action", "check")

  var rawServices = Seq[Service]()
  var discovered = new HashMap[String, String]()

  rawServices = systems.map(system => {
    try {
      val metaData = Json.deserialiseMetaDataResponse(HttpClient.unsafeGet(system.url + "/metadata"))
      //      println("actions: " + s.metaData.actions.size + ", checks: " + s.metaData.checks.size)

      var actions = new HashMap[String, String]()
      metaData.actions.map(service => {
        discovered = discovered.updated(service.url, system.url)
        actions = actions.updated(service.url, system.url)
      })

      var checks = new HashMap[String, String]()
      metaData.checks.map(service => {
        val fixedUpServices = service.url.split("/").dropWhile(!supportedServiceTypes.contains(_))
        val normalisedService = fixedUpServices.map(p => if (p.startsWith("@")) "@?" else p).mkString("/")
        val aliasedService = system.alias + "/" + normalisedService
        //        println("check: " + service + " -> " + aliasedService)
        discovered = discovered.updated(aliasedService, system.url)
        checks = checks.updated(aliasedService, system.url)
      })

      Some(Service(system, metaData))
    } catch {
      case _: Exception => println("### error discovering: " + system.url); None
    }
  }).flatten
}